package cn.tedu.lbs.marketing.web.service;

import cn.tedu.lbs.basic.api.BasicApi;
import cn.tedu.lbs.marketing.web.repository.CouponRepository;
import cn.tedu.lbs.marketing.web.utils.AuthenticationContextUtil;
import cn.tedu.lbs.stock.api.StockApi;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.marketing.param.CouponParam;
import com.tarena.lbs.pojo.marketing.po.CouponPO;
import com.tarena.lbs.pojo.marketing.query.CouponQuery;
import com.tarena.lbs.pojo.marketing.vo.CouponVO;
import com.tarena.lbs.pojo.stock.param.CouponStockParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CouponService {
    @Autowired
    private CouponRepository couponRepository;
    @DubboReference
    private StockApi stockApi;
    public PageResult<CouponVO> pageList(CouponQuery couponQuery) throws BusinessException {
        //1.拿到登录用户的id adminId
        Integer adminId = getUserId();
        //2.检查并获取 businessId
        Integer businessId = checkAndGetBusinessId(adminId);
        //3.利用businessId 查询该商家下的优惠券
        List<CouponPO> pos= getCouponsByBusinessId(businessId);
        //4.封装分页(假的)返回
        return assemblePageResult(pos);
    }

    private PageResult<CouponVO> assemblePageResult(List<CouponPO> pos) {
        PageResult<CouponVO> pageResult=new PageResult<>(10,1);
        pageResult.setTotal(100l);
        if (CollectionUtils.isNotEmpty(pos)){
            pageResult.setObjects(pos.stream().map(
                    po->{
                        CouponVO vo=new CouponVO();
                        BeanUtils.copyProperties(po,vo);
                        return vo;
                    }
            ).collect(Collectors.toList()));
        }else{
            pageResult.setObjects(null);
        }
        return pageResult;
    }

    private List<CouponPO> getCouponsByBusinessId(Integer businessId) {
        //select * from coupon where business_id=#{businessId}
        QueryWrapper<CouponPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("business_id",businessId);
        return couponRepository.list(queryWrapper);
    }

    //dubbo调用
    @DubboReference
    private BasicApi basicApi;
    private Integer checkAndGetBusinessId(Integer adminId) throws BusinessException {
        AdminDTO dto = basicApi.getAdminDetail(adminId);
        Asserts.isTrue(dto==null,new BusinessException("-2","商家账号不存在"));
        return dto.getBusinessId();
    }

    private Integer getUserId() throws BusinessException {
        //读取 认证 传递的userPrinciple 线程和过滤器线程相同
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        return userPrinciple.getId();
    }

    public void save(CouponParam couponParam) throws BusinessException {
        //1.拿到用户认证 adminId
        //2.检查并且获取businessId
        Integer businessId=checkAndGetBusinessId(getUserId());
        //3.param转化couponPO 补充数据
        CouponPO couponPO=assembleCouponPO(couponParam,businessId);
        //4.写入数据库
        couponRepository.save(couponPO);
        //5. 根据写入的优惠券 发行总量 初始化库存
        initCouponStock(couponPO);
    }

    private CouponPO assembleCouponPO(CouponParam couponParam, Integer businessId) {
        //1.能考被的全部拷贝
        CouponPO couponPO=new CouponPO();
        BeanUtils.copyProperties(couponParam,couponPO);
        //2.补充 businessId 保证优惠券和商家有所关联
        couponPO.setBusinessId(businessId);
        //status 优惠券状态 0 未发布 1已发布 2已过期等
        couponPO.setStatus(1);
        //enableStatus 管理状态 0 未启用 1启用
        couponPO.setEnableStatus(1);
        //创建时间 修改时间
        couponPO.setCreateAt(new Date());
        couponPO.setUpdateAt(new Date());
        //开始时间 结束时间 有效期
        //springmvc 默认接参 解析参数的逻辑 不能很好的处理时间字符串
        //"2025-02-17 10:10:00" Date LocalDateTime 如果用到 需要单独配置
        try {
            String startDate = couponParam.getStartDate();
            String endDate = couponParam.getEndDate();
            couponPO.setStartDate(DateUtils.parseDate(startDate, "yyyy-MM-dd HH:mm:ss"));
            couponPO.setEndDate(DateUtils.parseDate(endDate, "yyyy-MM-dd HH:mm:ss"));
        }catch (ParseException e){
            log.error("时间格式化失败",e);
        }
        return couponPO;
    }

    private void initCouponStock(CouponPO couponPO) {
        //1.po带的数据 整理成 初始化库存的入参
        CouponStockParam param=new CouponStockParam();
        param.setBusinessId(couponPO.getBusinessId());
        param.setCouponId(couponPO.getId());
        param.setNum(couponPO.getMaxUsageLimit());
        //2.调用api的方法
        stockApi.initCouponStock(param);
    }

    public CouponVO detail(Integer id) throws BusinessException {
        CouponPO po = couponRepository.getById(id);
        if (po!=null){
            CouponVO vo=new CouponVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }else{
            return null;
        }
    }
}
